#include "friendlist.h"
#include "ui_friendlist.h"
#include "changepersonalinfo.h"
#include "addfriendsender.h"
#include "addfriendreceiver.h"
#include "addfriendsearch.h"
#include "user.h"
#include "deletefriend.h"
#include <QHostAddress>
#include <QMessageBox>
void friendlist::closeEvent(QCloseEvent *)
{
    emit this->closefriendlistWidget();
}
friendlist::friendlist(QWidget *parent, user userSelf) :
    QWidget(parent),
    ui(new Ui::friendlist)
{
    ui->setupUi(this);
    this->userSelf = userSelf;
    this->setWindowTitle("好友列表");//添加标题
    //在界面添加个人信息
    ui->textBrowser_name->append(userSelf.getUserName());
    ui->textBrowser_id->append(userSelf.getUserId());
    ui->textBrowser_gender->append(userSelf.getUserGenderInChinese());
    ui->textBrowser_birthday->append(userSelf.getUserBirthday());


    // 创建网络访问管理器
    m_manager = new QNetworkAccessManager(this);

    // 创建标签以显示图像
    m_imageLabel = new QLabel(this);
    // 创建网络请求
    QNetworkRequest photoRequest(QUrl(this->userSelf.getUserPhoto()));
    m_manager->get(photoRequest);

    //设置头像
    m_imageLabel->setParent(ui->frame_photo);
    //填充QLabel容器
    m_imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QHBoxLayout *layout = new QHBoxLayout(ui->frame_photo);
    layout->addWidget(m_imageLabel);


    // 连接网络请求完成处理图片的信号
    connect(m_manager, &QNetworkAccessManager::finished, [=](QNetworkReply *reply){
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray imageData = reply->readAll();
            QPixmap pixmap;
            pixmap.loadFromData(imageData);
            m_imageLabel->setPixmap(pixmap);
            m_imageLabel->setScaledContents(true);
            emit downloaded(pixmap);
        } else {
            qWarning() << "Error downloading image:" << reply->errorString();
        }

        reply->deleteLater();
    });

    socket = new QWebSocket();//新建websocket

    QString resourcePath = ":/asset/config/config.json";
    QFile jsonFile(resourcePath);
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    QByteArray jsonData = jsonFile.readAll();
    // 将 JSON 数据转换为 QVariant 对象
    QJsonParseError error;
    QJsonObject result = QJsonDocument::fromJson(jsonData, &error).object();
    QJsonObject jsonUrl = QJsonDocument::fromJson(jsonData).object();
    qDebug() << "url :" << jsonUrl;
    jsonFile.close();
    QVariantMap urlVariantMap = jsonUrl.toVariantMap();
    QMap urlMap = urlVariantMap.value("server").toMap();
    host = urlMap.value("host").toString();
    port = urlMap.value("port").toString();
    }
    //好友列表
    //向后端发送信息
    QNetworkRequest request(QUrl("http://"+host+':'+port+"/slimarveous/get_friend_list"));//获取http地址

    //添加有新好友请求的提示
    friendLabel->setParent(ui->addfriendrequest);
    friendLabel->move(100,5);//设置坐标
    friendLabel->resize(10,10);//设置大小
    friendLabel->setStyleSheet("border-radius: 50%; background-color: red; ");
    friendLabel->setAlignment(Qt::AlignCenter);
    friendLabel->hide();
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json2");//设置传输文件
    QJsonObject json2
    {
        {"id",userSelf.getUserId().toInt()},
        {"username", userSelf.getUserName()},
        {"token", userSelf.getUserPassword()}
    };
    QJsonDocument doc(json2);
    QByteArray data = doc.toJson(QJsonDocument::Compact);//传输文件
    //获取http回复
    //QString message;
    //连接服务，处理相应数据
    QNetworkReply* reply = manager.post(request, data);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            // 读取响应数据
            QByteArray dataReply = reply->readAll();
            // 将 JSON 数据转换为 QVariant 对象
            QJsonParseError error;
            QJsonObject result = QJsonDocument::fromJson(dataReply, &error).object();
            // 处理 JSON 数据
            if(error.error == QJsonParseError::NoError)
            {
                QVariantMap resultMap = result.toVariantMap();
                //提取状态码
                QVariant status_code = resultMap.value("status_code");
                status_code.toString();
                QJsonArray friendList = resultMap.value("friends").toJsonArray();//处理好友的序列
                bool messageStatus[friendList.size()];//好友序列阅读消息状态
                for (int i = 0; i < friendList.size(); i++)
                    messageStatus[i] = 0;
                QLabel* ucMessageLabel = new QLabel[friendList.size()];
                for(int i = 0; i < friendList.size(); i++)//循环添加好友列表
                {
                    QJsonObject friendMap = friendList.at(i).toObject();
                    QVariant friendName = friendMap.value("username");
                    QVariant friendId = friendMap.value("id");
                    QVariant friendGender = friendMap.value("gender");
                    QVariant friendPhoto = friendMap.value("photo");
                    //qDebug()<<friendMap;
                    //qDebug()<<friendId;
                    QPushButton *friendButton = new QPushButton(friendName.toString(), this);//创建好友按钮
                    QPushButton *deleteFriendButton = new QPushButton(friendName.toString(), this);//创建删除好友按钮
                    //为每个好友按钮设置一个未读消息label
                    ucMessageLabel[i].setParent(friendButton);
                    ucMessageLabel[i].move(350,8);//设置坐标
                    ucMessageLabel[i].resize(15, 15);//设置大小
                    ucMessageLabel[i].setStyleSheet("border-radius: 50%; background-color: red; ");
                    ucMessageLabel[i].setAlignment(Qt::AlignCenter);
                    ucMessageLabel[i].hide();
                    //为每个好友设置删除按钮
                    deleteFriendButton->setParent(friendButton);
                    deleteFriendButton->setParent(friendButton);
                    deleteFriendButton->move(20,8);
                    deleteFriendButton->resize(20,20);
                    deleteFriendButton->setStyleSheet("QPushButton{font:20px;border-image: url(:/asset/image/delete.jpeg) stretch;}");
                    deleteFriendButton->setStyleSheet("QPushButton:hover{color: grey;border-image: url(:/asset/image/delete.jpeg) stretch;}");
                    deleteFriendButton->setText(" ");
                    for(int j = 0; j < messageQueue.size(); j++)//展示红点
                        if(messageQueue[j].messageSender == friendName.toString())
                            ucMessageLabel[i].show();   
                    QListWidgetItem *item = new QListWidgetItem(ui->listWidget_friend);//创建一个好友项
                    item->setSizeHint(friendButton->sizeHint()); // 设置列表项的大小
                    ui->listWidget_friend->setItemWidget(item, friendButton); // 将按钮控件添加到列表项中

                    //接受信息就显示红点
                    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
                    {
                        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
                        QJsonObject obj = doc.object();
                        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
                        //类型为chat
                        if (type == "chat")//如果为实时聊天
                        {
                            QVariantMap messageMap = obj.toVariantMap();//处理当时发送的消息
                            QMap senderMap = messageMap.value("sender").toMap();
                            QVariant senderName = senderMap.value("username");
                            if(senderName.toString() == friendName.toString())
                                ucMessageLabel[i].show();
                        }
                    });
                    // 在这里处理删除该好友
                    connect(deleteFriendButton, &QPushButton::clicked, this,[=]()//传入姓名 id
                    {
                        QVariantMap fMap = friendMap.toVariantMap();
                        QString tmp=fMap.value("id").toString();
                        QString tmp_name=fMap.value("username").toString();
                        deletefriend *df=new deletefriend(nullptr,userSelf,tmp,tmp_name);
                        df->show();
                    });
                    // 在这里处理和该好友对话的逻辑
                    connect(friendButton, &QPushButton::clicked, this,[=]()
                    {
                        ucMessageLabel[i].hide();
                        //创建新的聊天窗口
                        MainInterfaceWidget* mainWindow = new MainInterfaceWidget(nullptr, userSelf, friendName.toString(), friendId.toInt(), friendPhoto.toString(), socket);
                        mainWindow->setWindowTitle(friendName.toString());
                        mainWindow->setWindowIcon(QIcon(friendPhoto.toString()));
                        mainWindow->show();
                    });
                }

            }
        }
        else//出现问题
            qDebug()<<"error";
        reply->deleteLater();
    });

    connect(ui->addfriendsender,&QPushButton::clicked,this, &friendlist::addfriendsender_clicked);//好友添加
    connect(ui->addfriendsearch,&QPushButton::clicked,this, &friendlist::addfriendsearch_clicked);//好友搜索
    connect(ui->refresh,&QPushButton::clicked,this, &friendlist::refresh_clicked);//好友列表刷新
    connect(ui->addfriendrequest,&QPushButton::clicked,this, &friendlist::addfriendrequest_clicked);//好友列表刷新



    //QUrl url("ws://localhost:19999/slimarveous/ws");
    QUrl url("ws://"+host+':'+port+"/slimarveous/ws");//连接websocket地址



    QUrlQuery query;//在query里面添加id token两个信息，进而访问后端信息
    query.addQueryItem("id",userSelf.getUserId());
    query.addQueryItem("token",userSelf.getUserPassword());
    url.setQuery(query);
    socket->open(url);
    //连接到server
    QObject::connect(socket, &QWebSocket::connected,[=]()
    {
        qDebug() << "WebSocket connected";
    });
    //断开链接
    connect(this, &friendlist::closefriendlistWidget,this,[=](){
        socket->close();
    });
    QObject::connect(socket, &QWebSocket::disconnected, [=]()
    {
        qDebug() << "WebSocket disconnected";
    });

    //获取信息
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
    {
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
        //类型为chat
        if (type == "chat")//如果为实时聊天
        {
            QVariantMap messageMap = obj.toVariantMap();//处理当时发送的消息
            QMap senderMap = messageMap.value("sender").toMap();
            QVariant senderName = senderMap.value("username");
            int senderId = senderMap.value("id").toInt();
            QString senderPhoto = senderMap.value("photo").toString();
            QString receivedContent = obj.value("content").toString();
            QString receivedTime = obj.value("time").toString();
            //QString receiverPhoto = obj.value("photo").toString();

            Message chatMessage
            {
                this->userSelf.getUserName(),
                this->userSelf.getUserId().toInt(),
                this->userSelf.getUserPhoto(),
                receivedTime,
                senderName.toString(),
                senderId,
                senderPhoto,
                receivedContent
            };

            messageQueue.append(chatMessage);//添加到聊天处理队列里面
        }
        //类型为未读消息
        else if (type == "pull_chat")//如果为离线聊天
        {
            //将未读消息json文件转化成map

            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray ucMsg = pullChatMap.value("uc_messages").toJsonArray();
            for(int i = 0; i < ucMsg.size(); i++)
            {
                QJsonObject ucJsonObj = ucMsg.at(i).toObject();
                QVariantMap messageMap = ucJsonObj.toVariantMap();
                QMap senderMap = messageMap.value("sender").toMap();
                QVariant senderName = senderMap.value("username");
                int senderId = senderMap.value("id").toInt();
                QVariant senderPhoto = senderMap.value("photo");
                QString ucMsgContent = ucJsonObj.value("content").toString();
                QString ucMsgTime = ucJsonObj.value("time").toString();
                //qDebug() << ucJsonObj;
                Message ucMessage
                {
                    this->userSelf.getUserName(),
                    this->userSelf.getUserId().toInt(),
                    this->userSelf.getUserPhoto(),
                    ucMsgTime, senderName.toString(),
                    senderId,
                    senderPhoto.toString(),
                    ucMsgContent
                };
                messageQueue.append(ucMessage);
            }
        }
        else if (type == "add_friend")//接收到添加好友请求
        {
            QVariantMap messageMap = obj.toVariantMap();//处理信息
            addQueue.append(messageMap);
            friendLabel->show();
        }
        else if (type=="add_friend_fail_or_success")//在B同意或拒绝时处理数据，如果同意对双方发送消息，如果拒绝只对A发消息
        {
            QVariantMap messageMap = obj.toVariantMap();
            QMap receiverMap = messageMap.value("the_other").toMap();
            QVariant receiverName = receiverMap.value("username");
            QString add_friend_fail_or_success=obj.value("add_friend_fail_or_success").toString();
            QString message=obj.value("message").toString();
            if(message!="he/she refuse your request")
                QMessageBox:: information(this, "你向"+receiverName.toString()+"好友请求",message+" 请点击刷新好友列表按钮");//提示弹窗
            else
                QMessageBox:: information(this, "你向"+receiverName.toString()+"好友请求",message);
        }
        else if (type == "pull_friend_req")//离线处理好友请求
        {
            //将未读消息json文件转化成map
            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray reqQueue = pullChatMap.value("req_queue").toJsonArray();//转化为队列，处理请求
            for(int i = 0; i < reqQueue.size(); i++)
            {
                QJsonObject reqJsonObj = reqQueue.at(i).toObject();//转化为object
                QVariantMap messageMap = reqJsonObj.toVariantMap();//转化为map发送后端
                addQueue.append(messageMap);
                friendLabel->show();
            }
        }
    });
}

friendlist::~friendlist()
{
    delete ui;
}




//修改个人信息
void friendlist::on_toolButton_infChange_clicked()
{
    this->close();
    changepersonalinfo *cpi=new changepersonalinfo(nullptr,userSelf);
    cpi->show();
}
void friendlist::addfriendsender_clicked()
{
    addfriendsender *afs = new addfriendsender(nullptr, userSelf,"-1",0);
    afs->show();
}
void friendlist:: addfriendsearch_clicked()
{
    addfriendsearch *afsr = new addfriendsearch(nullptr, userSelf);
    afsr->show();
}
void friendlist:: addfriendrequest_clicked()
{
    for(int i=0;i<addQueue.size();i++)
    {
        addfriendreceiver *afr = new addfriendreceiver(nullptr, userSelf,addQueue[i],socket);
        afr->show();
    }
    addQueue.clear();
    friendLabel->hide();
}
void friendlist:: refresh_clicked()
{
    friendlist *fl=new friendlist(nullptr,userSelf);
    this->close();
    fl->show();
}
